<?php
/**
 * @file
 * Callbacks for services module resource hooks.
 */

/**
 * Callback for retrieving views resources.
 *
 * @param $view_name
 *   String. The views name.
 * @param $display_id
 *   String (optional). The views display name.
 * @param $args
 *   Array (optional). A list of arguments to pass to the view.
 * @param $offset
 *   Integer (optional). An offset integer for paging.
 * @param $limit
 *   Integer (optional). A limit integer for paging.
 * @param $return_type
 *   String (optional). Whether to return the raw data results (FALSE), the entire views object ('view') or themed results ('theme').
 * @param $filters
 *   Array (optional). A list of exposed filters to pass to the view.
 *
 * @return
 *  Array. The views return.
 */
function restapi_views_retrieve($view_name, $display_id = 'default', $args = array(), $offset = 0, $limit = -1, $return_type = FALSE, $filters = array()) {
  global $conf;
  $conf['theme_debug'] = 0;
  $result = array();

  $access = restapi_config_get('restapi-views-' . $view_name);
  if (empty($access)) {
    drupal_add_http_header(403, ' 403 Forbidden');
    return ;
  }
  $view = views_get_view($view_name);

  // Put all arguments and filters and then execute.
  $view->set_arguments($args, FALSE);
  $view->set_exposed_input($filters);
  $view->set_offset($offset);

  // Support for Views 2
  if (method_exists($view, 'set_use_pager')) {
    // If offset is set we can't have a user pager.
    if (empty($offset)) {
      $view->set_use_pager(TRUE);
      if ($limit >= 0) {
        $view->set_items_per_page($limit);
      }
    }
    else {
      // Disable the user pager.
      $view->set_use_pager(FALSE);
    }
  }
  elseif ($limit >= 0) {
    $view->set_items_per_page($limit);
  }

  // If we display values and not themed view output.
  if (empty($return_type)) {
    $view->set_display($display_id);
    foreach ($view->display['default']->handler->options['fields'] as $fn => $fv) {
      if (empty($fv['type'])) {
        continue;
      }

      if ($fv['type']  == 'field_collection_view') {
        $view->display['default']->handler->options['fields'][$fn]['type'] = 'jessica_fmt_rest_fe';
      }
      /*if ($view->display[$view->current_display]->handler->options['fields'][$fn]['type']  == 'taxonomy_term_reference_link') {
        $view->display[$view->current_display]->handler->options['fields'][$fn]['type'] = 'default';
      }*/
    }
    /*$view->display[$view->current_display]->handler->options['fields']['field_social_network']['type'] = 'jessica_fmt_rest_fe';
    $view->display[$view->current_display]->handler->options['fields']['field_category']['type'] = 'text';*/
    @$view->pre_execute();
    $view->preview($display_id);
    @$view->execute();

    $result = $view->result;

    $row_plugin = $view->display_handler->get_option('row_plugin');
    // If row plugin is node, then we should load each node
    if ($row_plugin == 'node') {
      $nodes = array();
      /*foreach ($view->result as $row) {
        $nodes[] = node_load($row->nid);
      }
      $result = $nodes;*/
    }
    elseif ($row_plugin == 'fields') {
      $items = array();
      foreach ($view->result as $row) {
        $item = new stdClass();
        foreach ($view->field as $field_id => $field) {
          if (!empty($view->field[$field->field]) && !empty($view->field[$field->field]->options['exclude'])) {
            continue;
          }
          $view->row_index = $field_id;
          if (!empty($field->api_alias)) {
            $field_label = $field->api_alias;
          }
          elseif (!empty($field->field_info['field_name'])) {
            $field_label = strtolower($field->field_info['field_name']);
          }
          elseif ($field->field_alias) {
            $field_label = $field->field_alias;
          }
          else {
            $field_label = $field_id;
          }
          if ($field_label == 'unknown') {
            if ($field->real_field == 'path') {
                $field_label = 'path';
            }
            else {
              continue;
            }
          }

          if (!empty($field->field_info) && $field->field_info['module'] == 'field_collection') {
            if (!empty($row->{'field_' . $field_id})) {
              foreach ($row->{'field_' . $field_id} as $rk => $rv) {
                $item->$field_label = @unserialize($rv['rendered']['#markup']);
              }
            }
          }
          else {
            $item->$field_label = $field->theme($row);
          }
        }
        $items[] = $item;
      }
      if ($items) {
        $result = $items;
      }
    }
  }
  elseif ($return_type == 'view') {
    $view->set_display($display_id);
    @$view->execute();
    return $view;
  }
  else {
    // We want to keep the result an array.
    $result[] = $view->preview($display_id);
  }
  $title = '';
  if (substr($view->current_display, 0, 5) == 'block') {
      $cblock = block_load('views', $view->name . '-' . $view->current_display);
      $title = !empty($cblock->title) ? $cblock->title : "";
  }
  return array('content' => $result, 'total_rows' => $view->total_rows, 'title' => $title);
}

/**
 * Execute a view and return results.
 */
function restapi_execute_view($view_info, $view = NULL, $display_id = NULL) {
  if (!empty($view_info)) {
    $view_name = $view_info['view_name'];
    $display_id = $view_info['display_id'];
    $args = $view_info['args'];

    $view = views_get_view($view_name);
    $view->set_arguments($args);
    $view->execute_display($display_id, $args);
  }

  // Avoid translation of the field labels.
  $view->localization_plugin = views_get_plugin('localization', 'none');

  // Execute a view.
  $output = $view->render($display_id);

  // Add support for Services Raw formatter.
  foreach ($view->result as $index => $row) {
    foreach ($view->field as $field_key => $field) {
      $f_key = 'field_' . $field_key;
      $entity_property = FALSE;
      if (!isset($row->$f_key)) {
        $f_key = $field->field_alias;
        $entity_property = TRUE;
      }
      if (isset($row->$f_key)) {
        $target_key = $field_key;

        // Skip this field?
        if (isset($field->options['exclude']) && $field->options['exclude'] == TRUE) {
          continue;
        }

        if (isset($field->options['label']) && !empty($field->options['label'])) {
          $target_key = $field->options['label'];
        }

        // Move key if we have an entity property and the target_key was changed via label
        if ($entity_property) {
          unset($output[$index]->$f_key);
          $output[$index]->$target_key = @$field->theme($row); // @todo: Do not render twice; use view->execute_display and consolidate functions
          continue;
        }

        // Create helper variables
        $output[$index]->$target_key = array();
        $obj = &$output[$index]->$target_key;
        $format = ($field->options['type'] == 'services') ? 'raw' : 'rendered';

        foreach ($row->$f_key as $idx => $res) {

          if (isset($res[$format])) {
            $data = $res[$format];

            // If this is raw formatter.
            if ($format == 'raw') {
              if (is_array($data)) {
                foreach ($data as $key => $val) {
                  if ($field->options['settings']['skip_safe'] && strpos($key, 'safe_') === 0) {
                    unset($data[$key]);
                  }
                  if ($field->options['settings']['skip_empty_values'] && empty($val)) {
                    unset($data[$key]);
                  }
                }
              }
              $obj[$idx] = $data;
            }
            // Rendered output.
            elseif (isset($data['#access']) && $data['#access'] == TRUE) {
              // Check for a field collection
              if (isset($data['entity']['field_collection_item'])) {
                foreach ($data['entity']['field_collection_item'] as $fcid => $entity) {
                  // If the field collection is using the services view mode,
                  // add each child separately.
                  if ($entity['#view_mode'] == 'services') {
                    $instances = field_info_instances($entity['#entity_type'], $entity['#bundle']);
                    foreach (element_children($entity, TRUE) as $child) {
                      $instance = $instances[$child];
                      $element_key = $instance['display']['services']['settings']['data_element_key'];
                      $element_key = ($element_key ? $element_key : $instance['label']);

                      // Get the formatted values for the field and add them to
                      // the data array, using any preset element keys.
                      foreach (element_children($entity[$child]) as $field_item) {
                        $fi = &$entity[$child][$field_item];
                        if (is_array($fi) && count($fi) == 1 && isset($fi['value'])) {
                          $obj[$idx][$element_key] = $fi['value'];
                        }
                        else {
                          $obj[$idx][$element_key] = $fi;
                        }
                      }
                    }

                    // Allow modules to alter the data before it is sent.
                    drupal_alter('services_field_collection_data', $obj[$idx], $entity, $f_key);
                  }
                  else {
                    $obj[$idx] = render($data);
                  }
                }
              }
              else {
                $obj[$idx] = render($data);
              }
            }
            else {
              $obj[$idx] = array('error' => t('Access denied or format unknown on field.'));
            }
          }
        }

        // Check cardinality of the field.
        if ($field->field_info['cardinality'] == 1 && count($obj) == 1) {
          $obj = $obj[$idx];
        }
      }
    }
  }

  drupal_alter('restapi_execute_view', $output, $view);

  $view->destroy();
  return $output;
}




function restapi_block_retrieve ($module, $delta) {
  $access = restapi_config_get('restapi-block-' . $module . '-' . $delta);
  if (empty($access)) {
    drupal_add_http_header(403, ' 403 Forbidden');
    return;
  }
  $q = parse_url($_SERVER['HTTP_REFERER']);
  if (empty($q)) {
    return;
  }
  $_GET['q'] = substr($q['path'], 1, strlen($q['path']));
  return bck_render_($module, $delta);
}




function restapi_block_region_retrieve ($region, $itheme) {
  global $theme;
  global $conf;
  $q = parse_url($_SERVER['HTTP_REFERER']);
  if (empty($q)) {
    return;
  }
  $conf['theme_debug'] = 0;
  $_GET['q'] = substr($q['path'], 1, strlen($q['path']));

  $block_list = block_list($region);

  $rets = array();
  $weight = 0;
  foreach($block_list as $block) {
    $ret = array();
    if ($block->module == 'views') {
      $v = $block->delta;
      $varr = explode('-', $v);
      $view_name = $varr[0];
      $display_id = $varr[1];
      $ret = restapi_views_retrieve($view_name, $display_id);
      $ret['block'] = $block->delta;
        $ret['html'] = FALSE;
    }
    else {
      $access = restapi_config_get('restapi-block-' . $block->module . '-' . $block->delta);
      if (empty($access)) {
        continue;
      }
      $renderable_block=  _block_get_renderable_array(array($block));
      $rb = drupal_render($renderable_block);
      if (!empty($rb)) {
        $ret['content'] = $rb;
        $ret['block'] = $block->delta;
        $ret['html'] = TRUE;
      }
    }
    $rets[] = $ret;
  }
  return $rets;
}







